package com.jzoom.zoom.admin.controllers;

import com.jzoom.zoom.admin.daos.UserDao;
import com.jzoom.zoom.admin.models.AccessService;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.dao.Page;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.web.action.ActionContext;
import com.jzoom.zoom.web.annotations.Controller;
import com.jzoom.zoom.web.annotations.JsonResponse;
import com.jzoom.zoom.web.annotations.Mapping;
import com.jzoom.zoom.web.annotations.Param;
import com.jzoom.zoom.web.exception.StatusException;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@Controller(key = "")
public class UserController extends BaseDaoController<UserDao> implements AdminController {

    @Inject
    private AccessService accessService;

    @Mapping("user/pass")
    @JsonResponse
    public void pass(ActionContext context, String oldPass, String newPass, String confirmPass) {
        if(oldPass ==null || newPass ==null || confirmPass == null){
            throw new StatusException.BadRequest();
        }

        if(!StringUtils.equals(newPass,confirmPass)){
            throw new StatusException.ApiError("确认密码必须和新密码一致");
        }

        String userId = context.get("userId",String.class);

        try {
            accessService.updatePass(userId,oldPass,newPass);
        } catch (AccessService.UserNotFoundException e) {
            throw new StatusException.ApiError("找不到这个用户");
        } catch (AccessService.PasswordException e) {
            throw new StatusException.ApiError("原密码错误");
        }
    }


    @Mapping(value = "sys/sys_user/index", method = {Mapping.POST})
    @JsonResponse
    public Page<Record> index(@Param(name = "@") Map<String, Object> params) {
        return model.getPage(params);
    }


    @Mapping(value = "sys/sys_user/list", method = {Mapping.POST})
    @JsonResponse
    public List<Record> list(
            @Param(name = "{ds}") String ds,
            @Param(name = "{module}") String module,
            @Param(name = "@") Map<String, Object> params) throws StatusException.NotFoundException {
        return model.getList(params);
    }
}
